<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row>
				<div class="flex justify-between w-full mb8">
					<el-space>
						<el-popover trigger="click" :width="550" placement="bottom-start">
							<el-form :inline="false" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef" label-width="90px" size="small">
								<el-row>
									<el-col :span="12" class="mb20">
										<el-form-item label="所属单位" prop="deptId">
											<el-tree-select
												v-model="state.queryForm.deptId"
												:data="parentData"
												:props="{ value: 'id', label: 'name', children: 'children', disabled: 'isLock' }"
												clearable
												filterable
												check-strictly
												:render-after-expand="false"
												placeholder="请选择所属单位"
												:teleported="false"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="12" class="mb20">
										<el-form-item label="单位限制" prop="deptLimit">
											<el-select clearable v-model="state.queryForm.deptLimit" :teleported="false">
												<el-option label="包含下级单位设备" :value="10" />
												<el-option label="仅本单位设备" :value="20" />
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="12" class="mb20">
										<el-form-item label="类型" prop="deviceTypeId">
											<el-select
												v-model="state.queryForm.deviceTypeId"
												clearable
												filterable
												placeholder="请选择设备类型"
												@change="getModelList"
												:teleported="false"
											>
												<el-option
													v-for="item in deviceTypeList"
													:key="item.id"
													:value="item.id"
													:label="item.typeName"
													:disabled="item.state === 20"
												/>
											</el-select>
										</el-form-item>
									</el-col>

									<el-col :span="12" class="mb20">
										<el-form-item label="设备型号" prop="deviceModelId">
											<el-select v-model="state.queryForm.deviceModelId" clearable filterable placeholder="请选择设备型号" :teleported="false">
												<el-option
													v-for="item in deviceModelList"
													:key="item.id"
													:value="item.id"
													:label="item.deviceModelName"
													:disabled="item.state === 20"
												/>
											</el-select>
										</el-form-item>
									</el-col>

									<el-col :span="12" class="mb20">
										<el-form-item label="建筑物" prop="buildingId">
											<el-select v-model="state.queryForm.buildingId" filterable placeholder="请选择" :teleported="false">
												<el-option v-for="item in buildingOptions" :key="item.id" :label="item.buildingName" :value="item.id" />
											</el-select>
										</el-form-item>
									</el-col>

									<el-col :span="12" class="mb20">
										<el-form-item label="安装点" prop="locationId">
											<el-select
												v-model="state.queryForm.locationId"
												filterable
												clearable
												remote
												reserve-keyword
												placeholder="请输入"
												remote-show-suffix
												:remote-method="remoteMethod"
												:teleported="false"
											>
												<el-option v-for="item in locationOptions" :key="item.id" :label="item.address" :value="item.id" />
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="12" class="mb20">
										<el-form-item label="设备状态" prop="deviceState">
											<el-select clearable v-model="state.queryForm.deviceState" :teleported="false">
												<el-option label="正常" :value="20" />
												<el-option label="故障" :value="30" />
												<el-option label="报警" :value="40" />
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="12" class="mb20">
										<el-form-item label="使用状态" prop="useState">
											<el-select clearable v-model="state.queryForm.useState" :teleported="false">
												<el-option label="正常使用" :value="10" />
												<el-option label="设备手动停用" :value="20" />
												<!-- <el-option label="设备到期停用" :value="30" /> -->
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="12" class="mb20">
										<el-form-item label="绑定状态" prop="bindState">
											<el-select clearable v-model="state.queryForm.bindState" :teleported="false">
												<el-option label="未出库未绑定" :value="10" />
												<el-option label="出库未绑定" :value="20" />
												<el-option label="已绑定" :value="30" />
											</el-select>
										</el-form-item>
									</el-col>

									<el-col :span="12" class="mb20">
										<el-form-item label="库存状态" prop="stocks">
											<el-select clearable v-model="state.queryForm.stocks" :teleported="false">
												<el-option label="已出库" :value="20" />
												<el-option label="库存" :value="10" />
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="24" class="mb20">
										<el-form-item label="注册时间" prop="createTime">
											<el-date-picker
												:end-placeholder="$t('syslog.inputEndPlaceholderTip')"
												:start-placeholder="$t('syslog.inputStartPlaceholderTip')"
												range-separator="To"
												type="datetimerange"
												v-model="state.queryForm.createTime"
												value-format="YYYY-MM-DD HH:mm:ss"
												:teleported="false"
											/>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form>

							<template #reference>
								<el-button link type="primary"
									>高级搜索<el-icon><ArrowDown /></el-icon>
								</el-button>
							</template>
						</el-popover>
						<el-input placeholder="请输入完整IMEI进行搜索" v-model="state.queryForm.imei" />
						<el-button type="primary" @click="getDataList(true)">搜索</el-button>
						<el-button icon="refresh" @click="resetQuery()"></el-button>
					</el-space>
					<div>
						<el-button class="mr-2" icon="Menu" type="primary" @click="handleColumnSetting"></el-button>
						<el-button type="success" v-auth="'platform_basicDevice_add'" class="mr-2" @click="formDialogRef.openDialog()"> 新增</el-button>
						<el-button plain v-auth="'platform_basicDevice_add'" class="ml10" icon="upload-filled" type="primary" @click="excelUploadRef.show()"
							>{{ $t('common.importBtn') }}
						</el-button>
						<!-- 更多操作 -->
						<el-popover :width="300">
							<template #reference>
								<el-button type="primary"
									>更多操作 <el-icon class="ArrowDown"><ArrowDown /></el-icon></el-button
							></template>
							<el-row>
								<el-col :span="12">
									<el-button class="ml-3" text icon="DeleteFilled" @click="handleDelete(selectObjs)" :disabled="multiple">删除设备</el-button>
									<el-button
										text
										icon="Remove"
										:disabled="multiple || selectObjs.length > 1 || selectObjs[0]?.useState === 20"
										@click="changeState(20)"
										>停用设备</el-button
									>
									<el-button
										text
										icon="RefreshLeft"
										:disabled="multiple || selectObjs.length > 1 || selectObjs[0]?.useState === 10"
										@click="changeState(10)"
										>取消停用</el-button
									>
								</el-col>
								<el-col :span="12">
									<el-button
										class="ml-3"
										text
										icon="CirclePlusFilled"
										:disabled="multiple || selectObjs.length > 1"
										@click="eventRecordDialogRef.openDialog(selectObjs[0].imei)"
										>事件记录
									</el-button>
									<el-button
										text
										icon="FolderDelete"
										:disabled="multiple || selectObjs.length > 1"
										@click="faultRecordDialogRef.openDialog(selectObjs[0].imei)"
										>故障记录</el-button
									>
									<el-button text icon="plus" :disabled="multiple" @click="handleBatchInstall(selectObjs)">批量绑定</el-button>
								</el-col>
							</el-row>
						</el-popover>
					</div>
				</div>
			</el-row>

			<el-table
				:data="state.dataList"
				v-loading="state.loading"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
				@sort-change="sortChangeHandle"
				@selection-change="selectionChangHandle"
			>
				<el-table-column type="selection" width="40" align="center" fixed="left" />
				<el-table-column type="index" label="序号" width="60" />
				<template v-for="item in columnInfo.columns">
					<el-table-column
						:show-overflow-tooltip="{ popperClass: 'max-w-[380px]' }"
						v-if="item.show"
						:key="item.prop"
						:prop="item.prop"
						:label="item.label"
						:width="item.width"
						:align="item.align"
					>
						<template #default="{ row }">
							<div v-if="item.prop === 'imeiQrCode'">
								<el-popover trigger="click" :width="324" title="设备IMEI二维码">
									<template #reference>
										<el-button link type="primary" icon="view">查看</el-button>
									</template>
									<vue-qrcode :value="row.imei" :options="{ width: 300, height: 300, margin: 2 }" />
								</el-popover>
							</div>
							<div class="flex justify-start" v-if="item.prop === 'imei'">
								<el-button icon="DocumentCopy" link type="primary" size="small" @click="copyText(row.imei)"></el-button>
								<el-button link type="primary" @click="imeiDetails(row)">{{ row.imei }}</el-button>
							</div>
							<div v-if="item.prop === 'deviceState'">
								<div v-if="row.online === 20">
									<div v-if="row.deviceState === 20" class="text-primary">正常</div>
									<div v-if="row.deviceState === 30" class="text-warning">故障</div>
									<div v-if="row.deviceState === 40" class="text-error">报警</div>
								</div>
								<div v-else class="text-info">离线</div>
							</div>
							<div v-if="item.prop === 'useState'">
								<div v-if="row.useState === 10" class="text-primary">正常使用</div>
								<div v-if="row.useState === 20" class="text-error">设备手动停用</div>
								<div v-if="row.useState === 30" class="text-error">设备到期停用</div>
							</div>
							<div v-if="item.prop === 'deviceType'">
								<span>{{ row.deviceType }}</span>
								<span class="px-1">-</span>
								<span>{{ row.deviceModelName }}</span>
							</div>
							<div v-if="item.prop === 'installAddress'">
								<el-button v-if="row.bindState !== 30" type="primary" size="small" @click="handleBind(row)">绑定</el-button>
								<span v-if="row.bindState === 30">{{ row.installAddress }}</span>
							</div>
							<span v-if="item.prop === 'deviceAttr'">
								<span v-for="item in row?.sensorTransmissionData?.sensorTransmissionDataDetailsList" :key="item.id" class="mr-1"
									>{{ item.sensorTypeName }}{{ item.sensorVal }}{{ item.sensorUnitName }}</span
								>
							</span>
							<div v-if="item.prop === 'deptName'">
								<div class="text-left">
									<el-popover placement="left" title="所属单位层级关系" :width="200" trigger="click">
										<div v-for="(item, index) in level" :key="item.id">【{{ index + 1 }}】{{ item.name }}</div>
										<template #reference>
											<el-button type="primary" @click="getListAncestorById(row.deptId)" icon="view" size="small" link></el-button>
										</template>
									</el-popover>

									{{ row.deptName }}
								</div>
							</div>
						</template>
					</el-table-column>
				</template>
			</el-table>
			<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
		</div>

		<!-- 编辑、新增  -->
		<form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
		<!-- 启用、禁用 -->
		<switch-form-dialog ref="switchFormDialogRef" @refresh="getDataList(false)" />
		<!-- 事件记录 -->
		<event-record-dialog ref="eventRecordDialogRef" />
		<!-- 故障记录 -->
		<fault-record-dialog ref="faultRecordDialogRef" />
		<!-- 绑定安装点 -->
		<install-form-dialog ref="installFormDialogRef" @refresh="getDataList(false)" />
		<!-- 表格排序 -->
		<column-setting ref="columnSettingRef" @refresh="handleSetColumns" @reset="handleResetColumns" /><!-- 导入 -->
		<!-- 导入 -->
		<upload-excel
			ref="excelUploadRef"
			title="导入传感器"
			temp-url="/admin/sys-file/local/file/basicDevice.xlsx"
			url="/platform/basicDevice/import"
			@refreshDataList="getDataList"
		/>
		<!-- 批量安装 -->
		<BatchInstallDialog ref="BatchInstallDialogRef" @refresh="getDataList(false)" />
	</div>
</template>

<script setup lang="ts" name="systemBasicDevice">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, delObjs } from '/@/api/platform/basicDevice';
import { fetchListAll } from '/@/api/platform/basicDeviceType';
import { fetchListAll as fetchAllModelList } from '/@/api/platform/basicDeviceModel';
import { fetchListAll as fetchBuildingListAll } from '/@/api/installation/basicPlaceBuilding';
import { fetchListAll as fetchLocationListAll } from '/@/api/installation/basicInstallLocation';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useRouter } from 'vue-router';
import { deptTree } from '/@/api/admin/dept';
import commonFunction from '/@/utils/commonFunction';
import { tableColumns, tableColumnsType } from './data';
import { fetchList as fetchColumnSettingList } from '/@/api/platform/basicCustomizeTable';
import { useUserInfo } from '/@/stores/userInfo';
import { getListAncestor } from '/@/api/admin/dept';
// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const SwitchFormDialog = defineAsyncComponent(() => import('./components/switchForm.vue'));
const BatchInstallDialog = defineAsyncComponent(() => import('./components/batchInstall.vue'));
const VueQrcode = defineAsyncComponent(() => import('@chenfengyuan/vue-qrcode'));
const EventRecordDialog = defineAsyncComponent(() => import('./components/eventRecord.vue'));
const faultRecordDialog = defineAsyncComponent(() => import('./components/faultRecord.vue'));
const ColumnSetting = defineAsyncComponent(() => import('./components/columnSetting.vue'));
const InstallFormDialog = defineAsyncComponent(() => import('/@/views/installation/basicInstallLocation/form.vue'));

const userStores = useUserInfo();
const { userInfos } = storeToRefs(userStores);

const router = useRouter();
const { copyText } = commonFunction();
const columnInfo = reactive<{ columns: tableColumnsType[]; id: string; tableName: string }>({
	columns: tableColumns,
	id: '',
	tableName: 'systemBasicDevice',
});
type levelItem = {
	id: string;
	name: string;
};
const level = ref<levelItem[]>([]);
// 定义查询字典

// 定义变量内容
const formDialogRef = ref();
const installFormDialogRef = ref();
const switchFormDialogRef = ref();
const eventRecordDialogRef = ref();
const faultRecordDialogRef = ref();
const columnSettingRef = ref();
const excelUploadRef = ref();
const BatchInstallDialogRef = ref();
// 搜索变量
const queryRef = ref();
// const showSearch = ref(true);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);
const currentRow = ref();
const deviceTypeList: any = ref([]);
const deviceModelList: any = ref([]);
const parentData = ref([]);
const buildingOptions = ref<any[]>([]);
const locationOptions = ref<any[]>([]);
// 新增设备弹窗
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: fetchList,
	descs: ['create_time'],
});
//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, tableStyle } = useTable(state);

// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	// 清空多选
	selectObjs.value = [];
	currentRow.value = null;
	multiple.value = true;
	state.queryForm.imei = '';
	getDataList();
};
onMounted(() => {
	getDeviceTypes();
});
// 获取设备数据
const getDeviceTypes = () => {
	fetchListAll({ state: 10 }).then((res) => {
		deviceTypeList.value = res.data;
	});
};
// 查询设备型号
const getModelList = (deviceTypeId: string) => {
	state.queryForm.deviceModelId = null;
	fetchAllModelList({ deviceTypeId, state: 10 }).then((res) => {
		deviceModelList.value = res.data;
	});
};
const getDeptData = async () => {
	deptTree().then((res) => {
		parentData.value = res.data;
	});
};
getDeptData();
const getBuildings = () => {
	fetchBuildingListAll().then((res) => {
		buildingOptions.value = res.data;
	});
};
const remoteMethod = (query: string) => {
	if (query) {
		fetchLocationListAll({ address: query }).then((res) => {
			locationOptions.value = res.data;
		});
	} else {
		locationOptions.value = [];
	}
};
getBuildings();
// IMEI详情;
const imeiDetails = (row: any) => {
	router.push({ path: '/platform/basicDevice/facilityDetails', query: { id: row.id, type: '1' } });
};

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
	selectObjs.value = objs;
	multiple.value = !objs.length;
};
// 删除操作
const handleDelete = async (ids: string[]) => {
	try {
		await useMessageBox().confirm('设备将彻底删除，确定继续吗');
	} catch {
		return;
	}

	try {
		await delObjs(ids);
		getDataList();
		useMessage().success('删除成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
// 启用停用
const changeState = async (state: number) => {
	if (selectObjs.value.length > 1) {
		useMessage().wraning('修改设备状态只能选择单条数据！');
		return false;
	}
	if (selectObjs.value.length === 0) {
		useMessage().wraning('请选择一条你要操作的数据！');
		return false;
	}
	const title = state === 20 ? '停用设备' : '启用设备';
	if (selectObjs.value[0].useState === state) {
		useMessage().wraning(`该设备目前为${title},请重新选择再操作！`);
		return false;
	}
	try {
		await useMessageBox().confirm(`此操作将${title}`);
	} catch {
		return;
	}
	unref(switchFormDialogRef).openDialog(selectObjs.value[0].id, selectObjs.value[0].useState, title);
};
const handleBind = (row: any) => {
	if (row.bindState === 10) {
		useMessage().error('该设备未出库，无法安装绑定或过户请联系设备供应商。');
		return;
	}
	installFormDialogRef.value.openDialog(row);
};
const handleBatchInstall = (rows: any[]) => {
	const hasBindState10 = rows.find((d) => d.bindState === 10);
	if (hasBindState10) {
		useMessage().error(hasBindState10.imei + '设备未出库，无法安装绑定或过户请联系设备供应商。');
		return;
	}
	const hasBindState30 = rows.findIndex((d) => d.bindState === 30);
	if (hasBindState30 !== -1) {
		useMessage().error('已绑定的设备不能再次进行绑定，请先完成解绑。');
		return;
	}
	BatchInstallDialogRef.value.openDialog(rows);
};
// 打开表格列设置弹窗
const handleColumnSetting = () => {
	columnSettingRef.value.openDialog(columnInfo.id, columnInfo.tableName, columnInfo.columns);
};
// 更新列表显示
const handleSetColumns = (data: tableColumnsType[]) => {
	columnInfo.columns = data;
	fetchColumnSettingList({ tableName: 'systemBasicDevice', userId: userInfos.value.user.userId, deptId: userInfos.value.user.deptId }).then((res) => {
		const d = res.data;
		columnInfo.id = d?.id;
	});
};
// 获取列表配置
const getColumnSetting = () => {
	fetchColumnSettingList({ tableName: 'systemBasicDevice', userId: userInfos.value.user.userId, deptId: userInfos.value.user.deptId }).then((res) => {
		if (res.data?.tableContent) {
			const d = res.data;
			columnInfo.id = d?.id;
			const cols_back = JSON.parse(d?.tableContent) as tableColumnsType[];

			const l = [] as tableColumnsType[];
			for (let i = 0; i < tableColumns.length; i++) {
				const item = tableColumns[i];
				const index = cols_back.findIndex((d) => d.prop === item.prop);
				if (index !== -1) {
					l.splice(index, 0, cols_back[index]);
				} else {
					l.splice(i, 0, item);
				}
			}

			columnInfo.columns = l;
		}
	});
};
const handleResetColumns = () => {
	columnInfo.columns = tableColumns;
	columnInfo.id = '';
};
getColumnSetting();
const getListAncestorById = (id: string) => {
	level.value = [];
	getListAncestor(id).then((res) => {
		level.value = res.data;
	});
};
</script>

<style scoped lang="scss"></style>
